<template>
  <t-skeleton :loading="loading">
    <div style="margin-bottom: var(--td-comp-margin-s)">
      <t-button
        @click="
          handleOpenDialog('create', {
            id: orderDetails.id,
            orderId: orderDetails.orderId,
            logType: 'plan',
            otherFileUrl: [],
            remark: plan.remark,
          })
        "
      >
        上传方案
      </t-button>
    </div>
    <t-alert v-if="plan.remark" style="margin-bottom: var(--td-comp-margin-s)">
      <span>备注：{{ plan.remark }}</span>
    </t-alert>
    <div class="content">
      <t-space direction="vertical" style="width: 100%">
        <t-collapse expand-mutex @change="handlePanelChange">
          <t-collapse-panel
            v-for="(file, index) in plan.fileUrls"
            :key="index"
            :value="index.toString()"
            :header="getListItemMeta(index, file.uploadTime)"
          >
            <!-- <t-space direction="vertical" size="large" style="width: 100%">
              <t-list :split="true">
                <t-list-item v-for="(file2, index2) in file.fileUrl" :key="index2">
                  <t-list-item-meta :image="(file2.type==='image/jpeg'||file2.type==='image/png')?file2.url:null" :title="file2.name" />
                  <template #action>
                    <t-button variant="text" shape="square" @click="downloadFile(file2.url)">
                      <download-icon />
                    </t-button>
                  </template>
                </t-list-item>
              </t-list>
            </t-space> -->
            <!-- <image-viewer :images="file.fileUrl.map((f: Record<string, string>) => f.url)" /> -->
              <div class="file-container">
                <template v-for="(file2, index) in file.fileUrl" :key="index">
                  <file-preview :file="file2" />
                </template>
              </div>
          </t-collapse-panel>
        </t-collapse>
      </t-space>
    </div>
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData }"
      :api-map="{ create: createSingleDesignInfo }"
      header="上传方案"
      width="700px"
      :on-before-save-data="handleDialogSaveData"
      @request-success="handleDialogRequestSuccess"
    >
      <!-- 居中 -->
      <t-form-item label="方案文件">
        <upload2 v-model:files="formData.otherFileUrl" />
        <!-- <upload v-model:files="formData.otherFileUrl" accept="image/*" multiple theme="image-flow" /> -->
      </t-form-item>
      <t-form-item label="备注" name="remark" :rules="[{ required: true, message: '请输入备注' }]">
        <t-textarea v-model:value="formData.remark" placeholder="请输入备注" />
      </t-form-item>
    </custom-dialog>
  </t-skeleton>
  <!-- 粘性审批对话框 -->
  <sticky-approve-dialog ref="stickyApproveDialogRef26" :order-id="orderDetails.orderId" approve-type="26" />
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { CollapseProps, MessagePlugin } from 'tdesign-vue-next';
import { DownloadIcon } from 'tdesign-icons-vue-next';
import { inject, onMounted, reactive, Ref, ref, useTemplateRef } from 'vue';

import { createSingleDesignInfo, getSingleDesignInfoList } from '@/api/order/single';
import CustomDialog from '@/components/custom/dialog/index.vue';
import ImageViewer from '@/components/image-viewer/index.vue';
import Upload from '@/components/upload/index.vue';
import Upload2 from '@/components/upload/index2.vue';
import StickyApproveDialog from '@/pages/approve/components/sticky-approve-dialog .vue';
import FilePreview from '@/components/file-preview/index.vue';
// import { useDictionaryStore, useUserStore } from '@/store';

// 用户仓库
// const userStore = useUserStore();
// // 字典仓库
// const dictionaryStore = useDictionaryStore();
// 订单详情
const orderDetails = inject<Ref<Record<string, any>>>('orderDetails');
// 容器类名
// const containerClassName = window.document.getElementsByClassName('view-order-scroll').length
//   ? '.view-order-scroll'
//   : '.tdesign-starter-layout';
// 加载状态
const loading = ref(false);
// 方案信息列表
const planList = ref([]);
// 方案信息
const plan = reactive({
  remark: '',
  result: null,
  fileUrls: [],
});

// 下载文件
const downloadFile = (url: string) => {
  // 浏览器打开url
  window.open(url);
};
const getListItemMeta = (index: number, uploadTime: string) => {
  return `第${index + 1}上传,上传时间为${dayjs(uploadTime).format('YYYY-MM-DD HH:mm:ss')}`;
};
const handlePanelChange: CollapseProps['onChange'] = (val) => {
  console.log(val);
};
// 处理获取方案信息列表
const handleGetplanList = () => {
  loading.value = true;
  const params = {
    orderId: orderDetails.value.orderId,
    logType: 'plan',
  };
  getSingleDesignInfoList(params)
    .then((data) => {
      if (!data) return;
      planList.value = data.fileUrls;
      plan.remark = data.remark;
      plan.result = data.result;
      plan.fileUrls = data.fileUrls;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    .finally(() => {
      loading.value = false;
    });
};
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  // 设置初始值

  customDialogRef.value.open(mode, params);
};
// 处理对话框保存数据
const handleDialogSaveData = (params: Record<string, any>) => {
  const hasWaitingFiles = params.otherFileUrl.some((item: any) => item.status === 'waiting');
  if (hasWaitingFiles) {
    MessagePlugin.warning('有文件待上传，请点击上传文件');
    return false;
  }
  return params;
};
// 处理对话框请求成功
const handleDialogRequestSuccess = () => {
  handleGetplanList();
};
// 粘性审批对话框ref  方案不用审批
const stickyApproveDialogRef26 = useTemplateRef('stickyApproveDialogRef26');
onMounted(() => {
  handleGetplanList();
  // const { approveType } = orderDetails.value;
  stickyApproveDialogRef26.value.open();
});
</script>

<style lang="less" scoped>
.content {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;

  .anchor {
    width: 150px;
    position: sticky;
    top: 100px;
  }

  .list {
    width: 100%;
  }
}
.file-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin: 12px 0;
}
</style>
